<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;

class Huzhuan extends Api{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function index(){
        $to_user_id = $this->request->param('to_user_id');
        $amount = $this->request->param('amount');
        if ($amount % 10 != 0) {
            $this->error('必须输入10的倍数');
        }
        $pay_password = $this->request->param('pay_password');
        $userinfo = $this->auth->getUserinfo();
        $userModel = new \app\admin\model\User();
        $userinfo = $userModel->where(['id'=>$userinfo['id']])->find()->toArray();
        /*if($userinfo['pay_password'] ==''){
            return json_encode([
                'code'=>101,
                'msg'=>'您还未设置交易密码',
                'data'=>[]
            ]);
        }
        $new_password = md5($pay_password);
        if($new_password!=$userinfo['pay_password']){
            $this->error('交易密码不正确');
        }*/
        if($amount>$userinfo['shouyi_balance']){
            $this->error('余额不足');
        }
        if($to_user_id==$userinfo['id']){
            $this->error('不能转给自己');
        }
        if($userinfo['is_freeze']==1){
            $this->error('您的帐户被冻结，不能互转');
        }
        //查一下转入用户是否存在
        $touserinfo=$userModel->where(['id'=>$to_user_id])->find();
        if(!$touserinfo){
            $this->error('转入用户不存在');
        }

        Db::startTrans();
        try{
            //先扣除我的余额
            $userModel->where(['id'=>$userinfo['id']])->update(['shouyi_balance'=>$userinfo['shouyi_balance']-$amount]);

            //增加对方余额
            $touserinfo=$touserinfo->toArray();
            $userModel->where(['id'=>$to_user_id])->update(['shouyi_balance'=>$touserinfo['shouyi_balance']+$amount]);

            //写入互转纪录
            $indata['from_user_id']=$userinfo['id'];
            $indata['to_user_id']=$to_user_id;
            $indata['amount']=$amount;
            $indata['create_time']=time();
            $huzhuanModel = new \app\admin\model\huzhuan\Huzhuan();
            $huzhuanModel->insert($indata);
            Db::commit();
            $this->success('成功');
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function huzhuanlist(){
        $userinfo = $this->auth->getUserinfo();
        $time = $this->request->param('time');
        $page = $this->request->param('page');
        // 添加页码检查
        if (empty($page) || $page < 1) {
            $page = 1;
        }

        // 添加时间格式验证
        if ($time && !strtotime($time)) {
            $this->error('时间格式不正确');
        }
        $pageSize = 10;
        $start = ($page - 1) * $pageSize;
        $huzhuanModel = new \app\admin\model\huzhuan\Huzhuan();

        $query = $huzhuanModel
            ->alias('h')
            ->field(
                'h.*, 
            fu.nickname as from_username, 
            fu.avatar as from_avatar,
            fu.id as from_id,
            tu.id as to_id,
            tu.nickname as to_username,
            tu.avatar as to_avatar'
            )
            ->join('user fu', 'fu.id = h.from_user_id', 'LEFT')
            ->join('user tu', 'tu.id = h.to_user_id', 'LEFT')
            ->where(function($query) use ($userinfo, $time) {
                if ($time) {
                    $timeStamp = strtotime($time);
                    // 明确使用括号分组
                    $query->where(function($q) use ($userinfo, $timeStamp) {
                        $q->where('h.from_user_id', $userinfo['id'])
                            ->where('h.create_time', '>', $timeStamp);
                    })->whereOr(function($q) use ($userinfo, $timeStamp) {
                        $q->where('h.to_user_id', $userinfo['id'])
                            ->where('h.create_time', '>', $timeStamp);
                    });
                } else {
                    // 没有时间参数时，查询所有相关记录
                    $query->where('h.from_user_id', $userinfo['id'])
                        ->whereOr('h.to_user_id', $userinfo['id']);
                }
            });

        $list = collection($query->limit($start, $pageSize)->order('h.create_time', 'desc')->select());
        if($list){
            $list = $list->toArray();
            $newlist = [];
            foreach ($list as $k => $v){
                $newlist[$k]['id'] = $v['id'];
                $newlist[$k]['amount'] = $v['amount'];
                $newlist[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                if($v['from_user_id'] == $userinfo['id']){
                    $newlist[$k]['type'] = 'HC转出';
                    if($v['from_avatar'] == ''){
                        $newlist[$k]['from_avatar'] = 'http://47.239.156.92/avatar.png';
                    } else {
                        $newlist[$k]['from_avatar'] = 'http://47.239.156.92/'.$v['to_avatar'];
                    }
                    $newlist[$k]['from_id'] = $v['to_id'];
                    $newlist[$k]['to_username'] = $v['to_username'];
                }elseif ($v['to_user_id'] == $userinfo['id']){
                    $newlist[$k]['type'] = 'HC转入';
                    if($v['from_avatar'] == ''){
                        $newlist[$k]['from_avatar'] = 'http://47.239.156.92/avatar.png';
                    } else {
                        $newlist[$k]['from_avatar'] = 'http://47.239.156.92/'.$v['from_avatar'];
                    }
                    $newlist[$k]['from_id'] = $v['from_id'];
                    $newlist[$k]['to_username'] = $v['from_username'];
                }else{
                    $newlist[$k]['type'] = 'HC转出';
                    $newlist[$k]['from_avatar'] = 'http://47.239.156.92/avatar.png';
                    $newlist[$k]['from_id'] = $v['from_id'];
                    $newlist[$k]['to_username'] = $v['from_username'];
                }
            }
            $this->success('成功', $newlist);
        } else {
            $this->success('成功', []);
        }
    }
}